<template>
    <div class="table">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/home' }"><i class="el-icon-menu"></i> 系统管理</el-breadcrumb-item>
                <el-breadcrumb-item>菜单管理</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="handle-box">
            <el-button type="primary" icon="delete" class="handle-del mr10" @click="add">新增</el-button>
            <el-button type="primary" icon="delete" class="handle-del mr10" @click="setAuthority">权限配置</el-button>
        </div>
        <el-table :data="roleList" border style="width: 100%" ref="multipleTable"
                  @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="45"></el-table-column>
            <el-table-column prop="code" label="编号" sortable>
            </el-table-column>
            <el-table-column prop="name" label="名称">
            </el-table-column>
            <el-table-column prop="pname" label="上级角色">
            </el-table-column>
            <el-table-column prop="deptName" label="所在部门">
            </el-table-column>
            <el-table-column prop="num" label="排序">
            </el-table-column>
            <el-table-column label="操作">
                <template scope="scope">
                    <el-button size="mini" type="primary"
                               @click="handleEdit(scope.$index, scope.row)">编辑
                    </el-button>
                    <el-button size="mini" type="primary"
                               @click="handleDelete(scope.$index, scope.row)">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination">
            <el-pagination
                @current-change="getData"
                :page-size="size"
                layout="total, prev, pager, next"
                :total="total">
            </el-pagination>
        </div>

        <!--新增弹框-->
        <el-dialog title="新增" :visible.sync="addFormVisible">
            <el-form :model="addForm" :inline="true" :rules="rules" ref="addForm" label-position="right"
                     class="demo-form-inline">
                <el-form-item prop="code" label="编号：" :label-width="formLabeWidth">
                    <el-input v-model="addForm.code" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item prop="name" label="名称：" :label-width="formLabeWidth">
                    <el-input v-model="addForm.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item prop="pid" label="上级角色：" :label-width="formLabeWidth">
                    <el-input v-model.number="addForm.pid" @focus="roleTreeFormVisible=true;"></el-input>
                </el-form-item>
                <el-form-item prop="deptid" label="所在部门：" :label-width="formLabeWidth">
                    <el-input v-model.number="addForm.deptid" @focus="deptTreeFormVisible=true;"></el-input>
                </el-form-item>
                <el-form-item prop="num" label="排序：" :label-width="formLabeWidth">
                    <el-input v-model.number="addForm.num" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="addSubmitForm('addForm')">确 定</el-button>
            </div>
        </el-dialog>
        <!--编辑弹框-->
        <el-dialog title="编辑" :visible.sync="editFormVisible">
            <el-form :model="editForm" :inline="true" :rules="rules" ref="editForm" label-position="right"
                     class="demo-form-inline">
                <el-form-item prop="code" required label="编号：" :label-width="formLabeWidth">
                    <el-input v-model="editForm.code" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item prop="name" label="名称：" :label-width="formLabeWidth">
                    <el-input v-model="editForm.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item prop="pid" label="上级角色：" :label-width="formLabeWidth">
                    <el-input v-model.number="editForm.pid" @focus="roleTreeFormVisible=true;"></el-input>
                </el-form-item>
                <el-form-item prop="deptid" label="所在部门：" :label-width="formLabeWidth">
                    <el-input v-model.number="editForm.deptid" @focus="deptTreeFormVisible=true;"></el-input>
                </el-form-item>
                <el-form-item prop="num" label="排序：" :label-width="formLabeWidth">
                    <el-input v-model.number="editForm.num" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="editSubmitForm('editForm')">确 定</el-button>
            </div>
        </el-dialog>
        <!--菜单（权限）树-->
        <el-dialog title="权限配置" :visible.sync="menuTreeVisible" width="30%" center>
            <el-tree
                :data="menuTreeDatas"
                show-checkbox
                :default-checked-keys="defaultChecked"
                node-key="id"
                ref="menuTree"
                highlight-current
                lazy
                :expand-on-click-node="false"
                :load="loadNode"
                @node-click="getKey"
                :props="defaultProps">
            </el-tree>
            <div slot="footer" class="dialog-footer">
                <el-button @click="menuTreeVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitSetAuthority">确 定</el-button>
            </div>
        </el-dialog>
        <!--部门树-->
        <el-dialog title="选择部门" :visible.sync="deptTreeFormVisible">
            <el-tree
                :data="deptTreeDatas"
                show-checkbox
                check-strictly
                node-key="id"
                ref="deptTree"
                highlight-current
                lazy
                :expand-on-click-node="false"
                :load="loadNodeDept"
                @node-click="getKeyDept"
                :props="defaultPropsDept">
            </el-tree>
            <div slot="footer" class="dialog-footer">
                <el-button @click="deptTreeFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="selectTreeDept">确 定</el-button>
            </div>
        </el-dialog>

        <!--角色树-->
        <el-dialog title="选择角色" :visible.sync="roleTreeFormVisible">
            <el-tree
                show-checkbox
                check-strictly
                node-key="id"
                ref="roleTree"
                highlight-current
                lazy
                :expand-on-click-node="false"
                :load="loadNodeRole"
                :props="roleProps">
            </el-tree>
            <div slot="footer" class="dialog-footer">
                <el-button @click="roleTreeFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="selectRole">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                multipleSelection: [],
                roleList: [],
                menuTreeDatas: [],
                defaultChecked: [],
                addFormVisible: false,
                editFormVisible: false,
                menuTreeVisible: false,
                deptTreeFormVisible: false,
                roleTreeFormVisible: false,
                deptTreeDatas: [],
                addForm: {
                    code: "",
                    name: "",
                    pid: "",
                    deptid: "",
                    num: ""
                },
                editForm: {
                    id: "",
                    code: "",
                    name: "",
                    pid: "",
                    deptid: "",
                    num: ""
                },
                formLabeWidth: '100px',
                rules: {
                    code: [
                        {required: true, message: '请输入编号', trigger: 'change'},
                    ],
                    name: [
                        {required: true, message: '请输入名称', trigger: 'change'}
                    ],
                    pid: [
                        {type: 'number', required: true, message: '请选择上级角色', trigger: 'change'}
                    ],
                    deptid: [
                        {type: 'number', required: true, message: '请选择部门', trigger: 'change'}
                    ],
                    num: [
                        {type: 'number', required: true, message: '请输入排序', trigger: 'change'}
                    ]
                },
                defaultProps: {
                    children: 'children',
                    label: 'name'
                },
                defaultPropsDept: {
                    children: 'children',
                    label: 'fullname'
                },
                roleProps: {
                    children: 'children',
                    label: 'name'
                },
                roleId: "",
                total: 0,
                currentPage: 1,
                size: 10
            }
        },
        created() {
            this.getData();
        },
        methods: {
            //获取role数据
            getData(data) {
                let self = this;
                var Vstart = 0;
                var Vsize = self.size;
                if (data != undefined && !isNaN(data)) {
                    Vstart = data - 1;
                }
                self.$axios.post("/api/role/get", {pageNumber: Vstart, pageSize: self.size}).then((res) => {
                    self.roleList = res.data.data.content;
                    self.total = res.data.data.totalElements;
                })
            },
            //新增面板
            add: function () {
                this.addFormVisible = true;
            },
            //添加角色
            addSubmitForm(formName) {
                const self = this;
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        self.$axios.post('/api/role/add', self.addForm)
                            .then(function (response) {
                                console.log(response);
                                self.$message({
                                    message: "添加成功",
                                    type: 'warning'
                                });
                                self.addFormVisible = false;
                                self.getData();
                            })
                            .catch(function (error) {
                                if (error.response) {
                                    self.$message({
                                        message: error.response.data.msg,
                                        type: 'error'
                                    });
                                }
                            })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            //编辑面板
            handleEdit(index, row) {
                const self = this;
                console.log(row);
                //self.$message('编辑第'+(index+1)+'行');
                self.editForm = row;
                self.editFormVisible = true;
            },
            //修改角色
            editSubmitForm(formName) {
                const self = this;
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        self.$axios.put('/api/role/update', self.editForm)
                            .then(function (response) {
                                console.log(response);
                                self.$message({
                                    message: "修改成功",
                                    type: 'warning'
                                });
                                self.editFormVisible = false;
                                self.getData();
                            })
                            .catch(function (error) {
                                if (error.response) {
                                    self.$message({
                                        message: error.response.data.msg,
                                        type: 'error'
                                    });
                                }
                            })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            //删除角色
            handleDelete(index, row) {
                const self = this;
                console.log(row.id);
                self.$confirm('确认删除吗？', '提示', {
                    type: 'warning'
                }).then(function () {
                    self.$axios.delete('/api/role/delete/' + row.id)
                        .then(function (response) {
                            console.log(response);
                            self.$message({
                                message: "删除成功",
                                type: 'warning'
                            });
                            self.getData();
                        })
                        .catch(function (error) {
                            if (error.response) {
                                self.$message({
                                    message: error.response.data.msg,
                                    type: 'error'
                                });
                            }
                        })
                })
            },
            //权限树形菜单加载
            loadNode: function (node, addNode) {
                const self = this;
                var pid;
                if (node.id == 0) {
                    pid = 0;
                } else {
                    pid = node.data.id;
                }
                this.$axios.get('/api/menu/selectMenuTreeList/' + pid)
                    .then(function (data) {
                        addNode(data.data.data);
                    })
                    .catch(function (error) {
                        if (error.response) {
                            self.$message({
                                message: error.response.data.msg,
                                type: 'error'
                            });
                        }
                    })
            },
            getKey: function (data, node) {
                console.log(data);
            },
            //打开树形菜单
            setAuthority() {
                const self = this;
                const length = self.multipleSelection.length;
                let str = '';
                if (length == 0) {
                    self.$message.error('请选择一项！');
                    return;
                }
                if (length > 1) {
                    self.$message.error('只能选择一项！');
                    return;
                }
                self.roleId = self.multipleSelection[0].id;

                self.getMenusIdByRoleId(self.roleId);
                self.menuTreeVisible = true;
            },
            //配置权限
            submitSetAuthority() {
                const self = this;
                var menusId = self.$refs.menuTree.getCheckedNodes();
                var menusIdStr = "";
                for (var i = 0; i < menusId.length; i++) {
                    menusIdStr += menusId[i].id + ",";
                }
                //console.log(menusIdStr);
                self.$axios.post('/api/role/setAuthority', {r_roleId: self.roleId, r_menuIds: menusIdStr})
                    .then(function (response) {
                        console.log(response);
                        self.$message({
                            message: "配置成功",
                            type: 'warning'
                        });
                        self.getData();
                    })
                    .catch(function (error) {
                        if (error.response) {
                            self.$message({
                                message: error.response.data.msg,
                                type: 'error'
                            });
                        }
                    })
                self.menuTreeVisible = false;
            },
            //设置树默认选中的值，代表当前角色已经有的权限
            getMenusIdByRoleId(roleId) {
                const self = this;
                this.$axios.get('/api/menu/getMenusIdByRoleId/' + roleId)
                    .then(function (response) {
                        self.defaultChecked = response.data.data;
                        //console.log(response.data.data);
                    })
                    .catch(function (error) {
                        if (error.response) {
                            self.$message({
                                message: error.response.data.msg,
                                type: 'error'
                            });
                        }
                    })
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            //树形部门加载
            loadNodeDept: function (node, addNode) {
                const self = this;
                console.log(node);
                var pid;
                if (node.id == 0) {
                    pid = 0;
                } else {
                    pid = node.data.id;
                }
                this.$axios.get('/api/dept/selectDeptTreeList/' + pid)
                    .then(function (data) {
                        addNode(data.data.data);
                    })
                    .catch(function (error) {
                        if (error.response) {
                            self.$message({
                                message: error.response.data.msg,
                                type: 'error'
                            });
                        }
                    })
            },
            getKeyDept: function (data, node) {
                console.log(data);
            },
            //选择部门
            selectTreeDept: function () {
                const self = this;
                var depts = self.$refs.deptTree.getCheckedNodes();
                if (depts.length == 0) {
                    self.$message.error('请选择一项！');
                    return;
                }
                if (depts.length > 1) {
                    self.$message.error('只能选择一项！');
                    return;
                }
                console.log(depts);
                self.addForm.deptid = depts[0].id;
                self.editForm.deptid = depts[0].id;
                self.deptTreeFormVisible = false;
            },
            //树形角色加载
            loadNodeRole: function (node, addNode) {
                const self = this;
                var pid;
                if (node.id == 0) {
                    pid = 0;
                } else {
                    pid = node.data.id;
                }
                this.$axios.get('/api/role/selectRoleTreeList/' + pid)
                    .then(function (data) {
                        addNode(data.data.data);
                    })
                    .catch(function (error) {
                        if (error.response) {
                            self.$message({
                                message: error.response.data.msg,
                                type: 'error'
                            });
                        }
                    })
            },
            //选择上级角色
            selectRole: function () {
                const self = this;
                var roles = self.$refs.roleTree.getCheckedNodes();
                if (roles.length == 0) {
                    self.$message.error('请至少选择一项！');
                    return;
                }
                if (roles.length > 1) {
                    self.$message.error('只能选择一项！');
                    return;
                }
                self.addForm.pid = roles[0].id;
                self.editForm.pid = roles[0].id;
                self.roleTreeFormVisible = false;
            },
        }
    }
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }
</style>
